import { showModel, showToast } from "../../utils/index.js"

Page({
  data: {
    address: {},
    cart: [],
    checkAll: false,
    totalPrice: 0,
    totalNum: 0
  },
  chooseAddress() {
    wx.chooseAddress({
      success: res => {
        wx.setStorageSync("address", res);
        this.setData({
          address: wx.getStorageSync("address")
        })
      }
    })
  },
  onShow() {
    let cart = wx.getStorageSync("cart") || []
    // 控制全选按钮是否选中，合并到forEach里
    // let checkAll = goods.length ? goods.every(v => v.check) : false
    this.setTotal(cart)
    this.setData({
      address: wx.getStorageSync("address"),
    })
  },
  handlecheckTap(e) {
    let { index } = e.currentTarget.dataset
    let { cart } = this.data
    cart[index].check = !cart[index].check
    this.setTotal(cart)
    wx.setStorageSync('cart', cart)

  },
  setTotal(cart) {
    let totalPrice = 0
    let totalNum = 0
    let checkAll = true
    checkAll = cart.length != 0 ? checkAll : false
    cart.forEach(v => {
      if (v.check) {
        totalPrice += v.goods_price * v.num
        totalNum += v.num
      } else {
        checkAll = false
      }
    })
    this.setData({
      cart,
      checkAll,
      totalPrice,
      totalNum
    })
    wx.setStorageSync('cart', cart)
  },
  handlecheckAll() {
    let { checkAll, cart } = this.data
    checkAll = !checkAll
    cart.forEach(v => v.check = checkAll)
    wx.setStorageSync("cart", cart)
    this.setData({
      checkAll,
      cart
    })
  },
  async handleNum(e) {
    let { operation, id } = e.currentTarget.dataset
    let { cart } = this.data
    let index = cart.findIndex(v => v.goods_id === id)
    if (cart[index].num === 1 && operation === -1) {
      // wx.showModal({
      //   title: '提示',
      //   content: '是否要删除商品',
      //   success: (res) => {
      //     if (res.confirm) {
      //       cart.splice(index, 1)
      //       this.setTotal(cart)
      //     } else if (res.cancel) {
      //       console.log('用户点击取消')
      //     }
      //     console.log(res);
      //   }
      // })
      const res = await showModel('是否要删除商品')
      if (res.confirm) {
        cart.splice(index, 1)
        this.setTotal(cart)
      } else if (res.cancel) {
        console.log('用户点击取消')
      }

    } else {
      cart[index].num += operation
      this.setTotal(cart)
    }
  },
  handlePay() {
    let { address, totalNum } = this.data
    if (!address.userName) {
      showToast('请输入收货地址')
      return
    }
    if (!totalNum) {
      showToast('请选择商品')
      return
    }
    wx.navigateTo({
      url: '/pages/pay/index'
    })
  }
})